package com.qianfeng.zookeeper.zookeeper;

//
//                            _ooOoo_  
//                           o8888888o  
//                           88" . "88  
//                           (| -_- |)  
//                            O\ = /O  
//                        ____/`---'\____  
//                      .   ' \\| |// `.  
//                       / \\||| : |||// \  
//                     / _||||| -:- |||||- \  
//                       | | \\\ - /// | |  
//                     | \_| ''\---/'' | |  
//                      \ .-\__ `-` ___/-. /  
//                   ___`. .' /--.--\ `. . __  
//                ."" '< `.___\_<|>_/___.' >'"".  
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |  
//                 \ \ `-. \_ __\ /__ _/ .-` / /  
//         ======`-.____`-.___\_____/___.-`____.-'======  
//                            `=---='  
//  
//         .............................................  
//                  佛祖镇楼                  BUG辟易  
//          佛曰:  
//                  写字楼里写字间，写字间里程序员；  
//                  程序人员写程序，又拿程序换酒钱。  
//                  酒醒只在网上坐，酒醉还来网下眠；  
//                  酒醉酒醒日复日，网上网下年复年。  
//                  但愿老死电脑间，不愿鞠躬老板前；  
//                  奔驰宝马贵者趣，公交自行程序员。  
//                  别人笑我忒疯癫，我笑自己命太贱；  
//  


import com.qianfeng.zookeeper.utils.ConnectionUtil;
import org.apache.zookeeper.*;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * Created by Jackiechan on 2022/6/29 11:38
 *
 * @author Jackiechan
 * @version 1.0
 * @since 1.0
 */
public class ZookeeperWatcher03 implements Watcher {
    private static ZooKeeper zooKeeper;
    private static CountDownLatch countDownLatch = new CountDownLatch(1);

    @Override
    public void process(WatchedEvent event) {
        System.err.println("ZookeeperWatcher03中的方法process 执行了");
        Event.EventType type = event.getType();
        Event.KeeperState state = event.getState();
        //受影响的路径
        String path = event.getPath();
        if (state == Event.KeeperState.SyncConnected) {
            switch (type) {
                case None:
                    System.err.println("连接成功");
                    break;
                case NodeCreated:
                    System.err.println(path + "创建成功");
                    try {
                        byte[] data = zooKeeper.getData(path, true, null);
                        System.err.println("当前创建的节点的数据是:" + new String(data));
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                    break;
                case NodeDataChanged:
                    System.err.println(path + "数据更新成功");
                    try {
                        byte[] data = zooKeeper.getData(path, true, null);
                        System.err.println("当前节点的新数据:" + new String(data));
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                    break;
                case NodeChildrenChanged:
                    //子节点发生变化,这里返回的是哪个父节点发生了变化
                    try {
                        List<String> children = zooKeeper.getChildren(path, true);
                        children.forEach(System.err::println);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }
        countDownLatch.countDown();
    }


    public static void main(String[] args) throws Exception {
        ZookeeperWatcher03 zookeeperWatcher03 = new ZookeeperWatcher03();
        //创建一个zookeeper
        zooKeeper = new ZooKeeper(ConnectionUtil.SERVER_ADDRESS, 30000, zookeeperWatcher03);
        countDownLatch.await();
       // zookeeperWatcher03.createPath("/04addressprovider", "创建的数据");
        // 读取数据
//        String data = zookeeperWatcher03.readData("/ceshijianting", true);
//        System.err.println(data);
//        //写数据
//        zookeeperWatcher03.writeData("/ceshijianting","老王是不是在发誓呢?");
        //我们获取了子节点,并且期望监听,肯定是子节点发生变化
        List<String> children = zookeeperWatcher03.getChildren("/04addressprovider", true);
        children.forEach(System.err::println);
        //创建一个子节点
//        zookeeperWatcher03.createChildren("/04addressprovider/192.168.3.131:10001", "随便写个数据");
        // 删除数据
        //zookeeperWatcher03.deletePath("/04addressprovider/192.168.3.131:10001");
        System.in.read();
        System.err.println("程序结束结束了");

    }

    /**
     * 创建节点
     *
     * @param path
     * @param data
     * @throws Exception
     */
    public void createPath(String path, String data) throws Exception {
        //提前声明说我要监听这个节点,true就是监听这个节点,如果这个节点在我们设置监听的时候还不存在,当存在的时候就会触发监听
        zooKeeper.exists(path, true);
        //我们发现直接创建,监听不会执行,原因是没有人监听过这个事情
        zooKeeper.create(path, data.getBytes(StandardCharsets.UTF_8), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    }

    /**
     * 获取某个节点的数据,如果希望后续的变化想要收到监听,可以设置允许监听
     *
     * @param path
     * @param watch
     * @return
     */
    public String readData(String path, boolean watch) throws Exception {
        byte[] data = zooKeeper.getData(path, watch, null);
        return new String(data);
    }


    public void writeData(String path, String data) throws Exception {
        zooKeeper.setData(path, data.getBytes(StandardCharsets.UTF_8), -1);
    }

    public List<String> getChildren(String parent, boolean watch) throws Exception {
        return zooKeeper.getChildren(parent, watch);
    }

    public void createChildren(String children, String data) throws Exception {

        //如果还想知道是哪个子节点创建了,就可以通过这个监听
        zooKeeper.exists(children, true);
        //我们发现直接创建,监听不会执行,原因是没有人监听过这个事情
        zooKeeper.create(children, data.getBytes(StandardCharsets.UTF_8), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    }

    public void deletePath(String path) throws Exception {
        zooKeeper.delete(path, -1);
    }
}
